package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.heima.model.User.dto.ApUserDto;
import com.heima.model.User.pojo.ApUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;


/**
 * @author 11494
 * @version 1.0
 * @project heima-leadnews
 * @date 2024/1/11 15:09:54
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult login(ApUserDto apUserDto) {
        //1.根据手机号查询用户
        LambdaQueryWrapper<ApUser> apUserLambdaQueryWrapper = Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone,apUserDto.getPhone());
        ApUser apUser = getOne(apUserLambdaQueryWrapper);
        //2.用户校验
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //2.1 校验手机号
        //2.2 校验密码 ,MD5(前端传的密码+盐) 和数据库的密码进行比较
        String inputPassword = DigestUtils.md5DigestAsHex((apUserDto.getPassword() + apUser.getSalt()).getBytes(StandardCharsets.UTF_8));
        if(inputPassword.equals(apUser.getPassword())){
            //2.3 比较成功,生成token返回
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            HashMap<String, Object> resultmap = new HashMap<>();
            apUser.setSalt(null);
            apUser.setPassword(null);
            resultmap.put("user",apUser);
            resultmap.put("token",token);
            return  ResponseResult.okResult(resultmap);
        }else {
            //2.3 比较失败,直接返回错误提示
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }
}
